package utils;


import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JBDCUtils {
    public static String driverClass;
    public static String url;
    public static String username;
    public static String password;

    static {
        try {
            //1.创建properties对象
            Properties pro=new Properties();
            //2.调用load方法加载配置文件
            InputStream is = JBDCUtils.class.getClassLoader().getResourceAsStream("db.properties");
            pro.load(is);
            //3.取值
            driverClass = pro.getProperty("driverClass");
             url = pro.getProperty("url");
             username = pro.getProperty("username");
             password = pro.getProperty("password");
            //注册驱动
            Class.forName(driverClass);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获得连接
     * @return
     * @throws Exception
     */
    public static Connection getConnection()throws  Exception{
        //获得连接
        Connection connection = DriverManager.getConnection(url,username,password);
        return connection;

    }

    /**
     * 释放资源
     * @param resultSet
     * @param statement
     * @param connection
     */
    public static void release(ResultSet resultSet, Statement statement, Connection connection){
        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }


}
